import React, {useEffect, useState, forwardRef, useImperativeHandle, useRef} from 'react';
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-react'
import style from './BlogContent.module.scss'
import {addBlogImg, addBlogVideo} from "../AddBlogApi";
import {store} from "../../../store/store";
import {message} from 'antd';
import {useSearchParams} from "react-router-dom";

const BlogContent = (props, ref) => {
    const [searchParams] = useSearchParams()

    // editor 实例
    const [editor, setEditor] = useState(null)
    // 编辑器内容
    const [htmlText, setHtmlText] = useState('hello')
    // 工具栏配置
    const toolbarConfig = {}
    // 编辑器配置
    const editorConfig = {
        placeholder: '请输入内容...',
        minHeight: '850px',
        scroll: false,
        fontSize: {
            'x-small': {name: '10px', value: '1'},
            'small': {name: '13px', value: '2'},
            'normal': {name: '16px', value: '3'},
            'large': {name: '18px', value: '4'},
            'x-large': {name: '24px', value: '5'},
            'xx-large': {name: '32px', value: '6'},
            'xxx-large': {name: '48px', value: '7'},
        },
        MENU_CONF: {
            //博客图片上传
            uploadImage: {
                // 自定义博客图片上传
                async customUpload(file, insertFn) {
                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                    if (!isJpgOrPng) {
                        message.error('你只能上传JPG/PNG文件!');
                        return false
                    }
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isLt2M) {
                        message.error('图片大小不能超过 2MB!');
                        return false
                    }

                    const formData = new FormData()
                    formData.append('file', file)
                    formData.append('blogUserId', store.getState().UserRedux.user.userNumber)
                    addBlogImg(formData).then(res => {
                        const imgUrl = process.env.REACT_APP_URL + res.data.url
                        insertFn(imgUrl)
                    })
                },
            },
            uploadVideo: {
                async customUpload(file, insertFn) {
                    console.log(file)
                    const type = ['video/mp4', 'video/mp3']
                    const isJpgOrPng = type.includes(file.type);
                    if (!isJpgOrPng) {
                        message.error('你只能上传mp3/mp4文件!');
                        return false
                    }
                    const isLt2M = file.size / 1024 / 1024 < 10;
                    if (!isLt2M) {
                        message.error('单个视频大小不能超过 10MB!');
                        return false
                    }
                    const formData = new FormData()
                    formData.append('file', file)
                    formData.append('blogUserId', store.getState().UserRedux.user.userNumber)
                    addBlogVideo(formData).then(res => {
                        const imgUrl = process.env.REACT_APP_URL + res.data.url
                        insertFn(imgUrl)
                    }).catch(e => {
                        console.log(e)
                    })
                }
            }
        }
    }

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    // 监听路由参数
    useEffect(() => {
        // 如果路由带id参数
        if (searchParams.has("id")) {
            setHtmlText(props.editBlog.blogContent)
        }
    }, [props.editBlog, searchParams])

    // 获取数据
    const getHtml = (editor) => {
        setHtmlText(editor.getHtml())
    }

    // 抛出数据
    useImperativeHandle(ref, () => {
        return {
            htmlText
        }
    })
    return (
        <div className={style.BlogContentBody}>
            <div>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{borderBottom: '1px solid #ccc'}}
                />
            </div>

            <div className={style.editorBody}>
                <div className={style.editorTextArea}>
                    <Editor
                        defaultConfig={editorConfig}
                        value={htmlText}
                        onCreated={setEditor}
                        onChange={getHtml}
                        mode="default"
                        style={{minHeight: '300px', overflowY: 'hidden', fontSize: '1rem'}}
                    />
                </div>
            </div>
        </div>
    );
}

export default forwardRef(BlogContent);
